package com.hu.utils;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * @功能：
 * @版本： V1
 * @版权： 信息技术有限公司（http://www.mychery.com/）
 * @作者： 磐石战队开发组  00355760
 * @日期： 2024/10/30 20:03
 */
public class ExceptionUtil {

    @ResponseBody
    @ExceptionHandler(value = IllegalArgumentException.class)
    public ActionResult exception(IllegalArgumentException e) {
        return ActionResult.fail(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = ConstraintViolationException.class)
    public ActionResult exception(ConstraintViolationException e) {
        return ActionResult.fail(this.errorDescForConstraintViolationException(e));
    }

    private String errorDescForConstraintViolationException(final ConstraintViolationException e) {
        return e.getConstraintViolations()
                .stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(","));
    }
}
